//
//  HealthSummaryGraphViewController.m
//  JiuLe
//
//  Created by 黄鑫 on 16/9/8.
//  Copyright © 2016年 Fine. All rights reserved.
//

#import "HealthSummaryGraphViewController.h"
#import "BaseChartView.h"
#import "NSString+Helper.h"
#import "VRGCalendarView.h"
#import "UWDatePickerView.h"
#import "HealthFootTableViewCell.h"
#import "GlossaryViewController.h"

@interface HealthSummaryGraphViewController ()<VRGCalendarViewDelegate,BaseChartViewDelegate>
@property (strong, nonatomic) UIButton *btnTyep;
@property (strong, nonatomic) UIButton *btnDay;
@property (strong, nonatomic) UIButton *btnWeek;
@property (strong, nonatomic) UIButton *btnMonth;
@property (strong, nonatomic) UIButton *btnData;
@property (strong, nonatomic) UIImageView *imageSelect;
@property (strong, nonatomic) BaseChartView *chartView;
@property (assign, nonatomic) BOOL brokenLine;
@property (nonatomic, strong) NSDate *selectDate;
@property (nonatomic, strong) UIView *maskView;
@property (nonatomic, strong) VRGCalendarView *pickerView;
@end

@implementation HealthSummaryGraphViewController
@synthesize chartView;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"计步";
    [self showNavgationWithLeftItemWithTitle:@"健康数据"];
    self.stepCount = @"0";
    [self showNavBarWithRightImage:[UIImage imageNamed:@"icon_help"] andRightBtnAction:@selector(helpAction)];
    _arrModel = [NSMutableArray array];
    _requestDateType = RequestDateTypeDay;
    [self arrModelDataFill];
    _arrXAxisMark = [NSMutableArray arrayWithObjects:@"00:00",@"08:00",@"16:00",@"24:00",nil];
    _selectDate = [NSDate date];
    NSString *time = [NSString stringTime:_selectDate];
    [self getHealthData:time endDate:time];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    [self initBtton];
    [self setSelectImage];
    UILabel *lab = [self.view viewWithTag:10];
    lab.attributedText = [self setLabelText:[NSString stringWithFormat:@"%@步",self.stepCount] perUnitLength:1];
}

#pragma mark  - 数据请求
- (void)getHealthData:(NSString *)startDate endDate:(NSString *)endDate{
    [SVProgressHUD showWithStatus:@"获取计步数据.." maskType:SVProgressHUDMaskTypeClear];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:UserDataID] forKey:@"user_id"];
    [dict setObject:startDate forKey:@"start_date"];
    [dict setObject:endDate forKey:@"end_date"];
    [dict setObject:@"0" forKey:@"health_type"];
    [[BaseDataRequest alloc] getDetailedHealthData:dict WithBlock:^(id responseObject, NSString *status, NSError *error) {
        [SVProgressHUD dismiss];
        if ([status isEqualToString:@"0"]){
            _arrYAxis =[NSMutableArray array];
            NSMutableDictionary *result = [responseObject objectForKey:@"result"];
            NSMutableDictionary *detail = [result objectForKey:@"detail"];
            if([detail allKeys].count == 0){
                TIPSFORVIEW(@"暂无数据");
                _requestDateType = _previousRequestDateType;
                return ;
            }
            _previousRequestDateType = _requestDateType;
            NSMutableArray *keys = [NSMutableArray arrayWithArray:[detail allKeys]];
            [keys sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                if ([obj1 integerValue] > [obj2 integerValue]) {
                    return NSOrderedDescending;
                }else if ([obj1 integerValue] < [obj2 integerValue]){
                    return NSOrderedAscending;
                }else {
                    return NSOrderedSame;
                }
            }];
            [keys enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (_requestDateType == RequestDateTypeDay) {
                    NSString *time ;
                    time = [obj substringToIndex:2];
                    NSString *minute ;
                    minute = [obj substringFromIndex:2];
                    int index = ([time intValue]*12) + ([minute intValue]/5);
                    [_arrModel replaceObjectAtIndex:(index) withObject:[detail objectForKey:obj]];
                }else{
                    NSMutableString *str = [[NSMutableString alloc]initWithFormat:@"%@",obj];
                    [str insertString:@"/"atIndex:2];
                    for (int i = 0; i < _arrXAxisMark.count; i++) {
                        if ([_arrXAxisMark[i] isEqualToString:str]) {
                            [_arrModel replaceObjectAtIndex:i withObject:[detail objectForKey:obj]];
                        }
                    }
                }
            }];
            _stepCount = _arrModel[[self backIndex:_arrModel]];
            self.arrYAxis =[_arrModel copy];
            [self.tableView reloadData];
            [self setSelectImage];
        }else{
            if (error != nil) {
                TIPSFORVIEW(@"请检测网络设置");
            }else{
                TIPSFORVIEW(@"获取计步数据失败");
            }
        }
    }];
}

#pragma  mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row == 0){
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HealthViewCell0" forIndexPath:indexPath];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"HealthViewCell"] ;
        }
        self.btnDay = [cell viewWithTag:2];
        self.btnWeek = [cell viewWithTag:3];
        self.btnMonth = [cell viewWithTag:4];
        self.btnData = [cell viewWithTag:5];
        self.imageSelect = [cell viewWithTag:6];
        //UILabel *lab = [cell viewWithTag:10];//步数
        //UILabel *labDistance = [cell viewWithTag:11];//距离
        //UILabel *labHeat = [cell viewWithTag:12];//热量
        UILabel *labDate = [cell viewWithTag:13];//时间
        UILabel *labTime = [cell viewWithTag:111];//日历时间
        //lab.attributedText = [self setLabelText:[NSString stringWithFormat:@"%@步",_stepCount] perUnitLength:1];
        //labDistance.text = [NSString stringWithFormat:@"%@公里",_strDistance];
        //labHeat.text = [NSString stringWithFormat:@"%@千卡",_strHeat];
        labDate.text = [NSString stringThatDay:_selectDate];
        if (_requestDateType == RequestDateTypeDay) {
            labTime.text = [NSString stringTime:_selectDate];
        }else if(_requestDateType == RequestDateTypeWeek){
            labTime.text = [NSString stringWeek:[NSDate date]];
        }else{
            labTime.text = [NSString stringMonth:[NSDate date]];
        }
        return cell;
    }else if(indexPath.row == 1){
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HealthViewCell1" forIndexPath:indexPath];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"HealthViewCell1"] ;
        }
        if (self.arrYAxis.count != 0) {
            chartView = [[BaseChartView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH)];
            chartView.delegate = self;
            int type = _requestDateType;
            NSMutableArray *arrY = [NSMutableArray arrayWithObjects:@"0",@"10000",@"20000",@"30000",nil];
            if(_requestDateType == RequestDateTypeAge){
                NSMutableArray *arrExtraction = [NSMutableArray array];
                int index = 0;
                while (index < self.arrXAxisMark.count) {
                    [arrExtraction addObject:self.arrXAxisMark[index]];
                    index += 4;
                }
                chartView.xAxisMark  = arrExtraction;
            }else{
                chartView.xAxisMark  = self.arrXAxisMark;
            }
            chartView.yAxisMark  = arrY;
            chartView.yAxis      = self.arrYAxis;
            chartView.baseChartType = self.brokenLine?BaseChartTypeHistogram:BaseChartTypeLineChart;
            chartView.baseChartShowDate  = type;
            chartView.baseChartShowDateType = BaseChartShowDateTypePedometer;
            [chartView startDraw];
            [cell.contentView addSubview:chartView];
        }
        return cell;
    }else{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HealthViewCell2" forIndexPath:indexPath];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"HealthViewCell2"] ;
        }
        self.btnTyep = [cell viewWithTag:1];
        UIButton *btnMeasuring = [cell viewWithTag:2];
        btnMeasuring.hidden = YES;
        return cell;
    }
}

#pragma mark - tableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 242;
    }else if(indexPath.row == 1){
        return  SCREEN_WIDTH-100;
    }else{
        return 44;
    }
}

#pragma mark - VRGCalendarView Delegate
-(void)calendarView:(VRGCalendarView *)calendarView
    switchedToMonth:(int)month
       targetHeight:(float)targetHeight
           animated:(BOOL)animated {
}

- (void)calendarView:(VRGCalendarView *)calendarView dateSelected:(NSDate *)date {
    [self hiddenPickerView];
    _selectDate = date;
    _requestDateType = RequestDateTypeDay;
    [self arrModelDataFill];
    _arrXAxisMark = [NSMutableArray arrayWithObjects:@"00:00",@"08:00",@"16:00",@"24:00",nil];
    [self getHealthData:[NSString stringTime:_selectDate] endDate:[NSString stringTime:_selectDate]];
}

#pragma mark - BaseChartViewDelegate
- (void)backData:(NSString *)number withTime:(NSString *)time{
    _stepCount = number;
    UILabel *lab = [self.view viewWithTag:10];
    UILabel *labDate = [self.view viewWithTag:13];
    UILabel *labTime = [self.view viewWithTag:111];
    lab.attributedText = [self setLabelText:[NSString stringWithFormat:@"%@步",number] perUnitLength:1];
    if (_requestDateType == RequestDateTypeDay) {
        labTime.text = [NSString stringWithFormat:@"%@ %@",[NSString stringTime:_selectDate],time];
    }else{
        labTime.text = time;
        labDate.text = [NSString stringThatDay:[NSString stringToDate:time]];
    }
    if([number intValue] >= 0 ){
        float distance,heat;
        NSString *height =  [[NSUserDefaults standardUserDefaults]objectForKey:UserHeight];
        NSString *weight = [[NSUserDefaults standardUserDefaults]objectForKey:UserWeight];
        if([[[NSUserDefaults standardUserDefaults]objectForKey:UserSex] intValue] == 0){//女
            distance = [number floatValue]*(0.413)*[height floatValue]/100000;
            heat = [weight floatValue]*distance*1.036;
        }else{
            distance = [number floatValue]*(0.415)*[height floatValue]/100000;
            heat = [weight floatValue]*distance*1.036;
        }
        UILabel *labDistance = [self.tableView viewWithTag:11];
        UILabel *labHeat = [self.tableView viewWithTag:12];
        labDistance.text = [NSString stringWithFormat:@"%.1f公里",distance];
        labHeat.text = [NSString stringWithFormat:@"%.1f千卡",heat];
    }
}

#pragma mark - 私有方法
- (void)initBtton{
    [self.btnTyep addTarget:self action:@selector(tipAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.btnDay addTarget:self action:@selector(tipAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.btnWeek addTarget:self action:@selector(tipAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.btnMonth addTarget:self action:@selector(tipAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.btnData addTarget:self action:@selector(tipAction:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)tipAction:(UIButton *)btn{
    _previousRequestDateType = _requestDateType;
    if (btn.tag == 1) {
        if(self.brokenLine == NO){
            chartView.baseChartType = BaseChartTypeHistogram;
            [btn setTitle:@"折线图" forState:UIControlStateNormal];
        }else{
            chartView.baseChartType = BaseChartTypeLineChart;
            [btn setTitle:@"柱状图" forState:UIControlStateNormal];
        }
        self.brokenLine = !self.brokenLine;
        [chartView startDraw];
    }else if (btn.tag == 2){
        _requestDateType = RequestDateTypeDay;
        [self arrModelDataFill];
        _arrXAxisMark = [NSMutableArray arrayWithObjects:@"00:00",@"08:00",@"16:00",@"24:00",nil];
        _selectDate = [NSDate date];
        [self getHealthData:[NSString stringTime:_selectDate] endDate:[NSString stringTime:_selectDate]];
    }else if (btn.tag == 3){
        _requestDateType = RequestDateTypeWeek;
        [self arrModelDataFill];
        _selectDate = [NSDate date];
        _arrXAxisMark = [NSString getArrayDates:_selectDate type:@"周"];
        _arrXAxisMark = (NSMutableArray *)[[_arrXAxisMark reverseObjectEnumerator] allObjects];
        [self getHealthData:[NSString stringWeek:[NSDate date]] endDate:[NSString stringTime:[NSDate date]]];
    }else if (btn.tag == 4){
        _requestDateType = RequestDateTypeAge;
        [self arrModelDataFill];
        _selectDate = [NSDate date];
        _arrXAxisMark = [NSString getArrayDates:_selectDate type:@"月"];
        _arrXAxisMark = (NSMutableArray *)[[_arrXAxisMark reverseObjectEnumerator] allObjects];
        [self getHealthData:[NSString stringMonth:[NSDate date]] endDate:[NSString stringTime:[NSDate date]]];
    }else if (btn.tag == 5){
        [self setupDateView:DateTypeOfStart];
    }
}

- (void)setupDateView:(DateType)type{
    if (_pickerView == nil) {
        _maskView = [[UIView alloc] initWithFrame:self.view.bounds];
        [_maskView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                action:@selector(hiddenPickerView)]];
        _maskView.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.4];
        [self.view addSubview:_maskView];
        _maskView.tag = 0x22;
        _pickerView = [[VRGCalendarView alloc] initWithFrame:CGRectMake(CGRectGetWidth(self.view.bounds)/2 - kVRGCalendarViewWidth/2, CGRectGetHeight(self.view.frame)/2 - 271 / 2, kVRGCalendarViewWidth, 0)];
        _pickerView.delegate = self;
        [self.view addSubview:_pickerView];
    } else {
        [self hiddenPickerView];
        [self.view addSubview:_pickerView];
    }
}

- (void)hiddenPickerView {
    _pickerView.hidden = !_pickerView.hidden;
    _maskView.hidden = _pickerView.hidden;
}

- (NSMutableAttributedString *)setLabelText:(NSString *)text perUnitLength:(int)length{
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc]initWithString:text];
    [attributedStr addAttribute:NSFontAttributeName
                          value:[UIFont systemFontOfSize:16.0]
                          range:NSMakeRange(text.length - length, length)];
    return attributedStr;
}

- (void)arrModelDataFill{
    [_arrModel removeAllObjects];
    if (_requestDateType == RequestDateTypeDay) {
        int i = 0;
        while ( i < 288) {
            [_arrModel addObject:@"-1"];
            i ++;
        }
    }else if (_requestDateType == RequestDateTypeWeek){
        for (int i = 0; i < 7; i++) {
            [_arrModel addObject:@"0"];
        }
    }else{
        for (int i = 0; i < 29; i++) {
            [_arrModel addObject:@"0"];
        }
    }
}

- (void)setSelectImage{
    if (_requestDateType == RequestDateTypeDay) {
        self.imageSelect.frame = CGRectMake(0, CGRectGetMinY(self.imageSelect.frame), (SCREEN_WIDTH - 39)/3, CGRectGetHeight(self.imageSelect.frame));
    }else if (_requestDateType == RequestDateTypeWeek){
        self.imageSelect.frame = CGRectMake((SCREEN_WIDTH - 39)/3, CGRectGetMinY(self.imageSelect.frame), (SCREEN_WIDTH - 39)/3, CGRectGetHeight(self.imageSelect.frame));
    }else{
        self.imageSelect.frame = CGRectMake(2*(SCREEN_WIDTH - 39)/3, CGRectGetMinY(self.imageSelect.frame), (SCREEN_WIDTH - 39)/3, CGRectGetHeight(self.imageSelect.frame));
    }
}

- (void)helpAction{
    GlossaryViewController *glossary = [[GlossaryViewController alloc] initWithNibName:@"GlossaryViewController" bundle:nil];
    glossary.strTitle = @"计步";
    [self.navigationController pushViewController:glossary animated:YES];
}

- (NSInteger)backIndex:(NSMutableArray *)arr{
    NSInteger index = 0;
    for (int i = 0 ; i < arr.count; i++) {
        if ([arr[i] intValue]> -1) {
            index = i;
            break;
        }
    }
    return index;
}

#pragma mark - set/get
- (NSMutableArray *)arrYAxis{
    if (_arrYAxis == nil) {
        _arrYAxis = [NSMutableArray array];
    }
    return _arrYAxis;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
